package com.cloudfun.campusshare.repo;

import com.cloudfun.campusshare.entity.CouponPromotionEntity;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Created by CodeGenerator on 2020/06/06
 */
public interface CouponPromotionRepo extends PagingAndSortingRepository<CouponPromotionEntity, String>, JpaSpecificationExecutor<CouponPromotionEntity> {

    Long countAllByCouponId(String couponId);

    CouponPromotionEntity findByPromotionId(String couponId);

    @Modifying
    @Transactional
    @Query(value = "update coupon_promotion c set c.issued_quantity=c.issued_quantity+:issuedNum where c.id=:id and c.total_quantity>=c.issued_quantity+:issuedNum" +
            " and c.account_draw_quantity>=(select count(uc.id) from user_coupon uc where uc.promotion_id=c.promotion_id and user_id=:customerId)", nativeQuery = true)
    int updateIssuedQuantity(@RequestParam("id") String id, @RequestParam("issuedNum") Integer issuedNum, @RequestParam("customerId") String customerId);
}